import numpy as np


S = ['A', 'B', 'C', 'D', 'E']
P = [0.04, 0.1, 0.02, 0.3, 0.02, 0.1, 0.05, 0.2, 0.06, 0.1, 0.01]

n = len(S)
m = np.zeros((n+1, n+1))
K = np.zeros((n+1, n+1))

for k in range(n):
    for h in range(n-k):
        i,j=h+1,h+k+1
        w = sum(P[(i-1)*2:(j)*2+1])
        mk = sum(np.array([m[i-1,i-1:j],m[i:j+1,j]]), 0)
        mmk = min(mk)
        K[i-1,j] = np.where(mk == mmk)[0][0]+h+1
        m[i-1,j]=mmk+w

print("m矩阵：")
print(m)
print("K矩阵：")
print(K)